package com.kqb.sgcommon.file.config;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.kqb.sgcommon.file.config.properties.OSSProperties;
import com.kqb.sgcommon.file.oss.impl.FileServiceImpl;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author 杉果树皮
 */
@AutoConfiguration
@ConditionalOnProperty(name = "oss.enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(OSSProperties.class)
@Import(FileServiceImpl.class)
public class OSSConfig {

    @Resource
    private OSSProperties ossProperties;

    @Bean
    public OSS ossClient() {
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider(ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        return OSSClientBuilder.create()
                .credentialsProvider(defaultCredentialProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(ossProperties.getRegion())
                .endpoint(ossProperties.getEndpoint())
                .build();
    }

    @PreDestroy
    public void destroy() {
        // Spring 容器关闭时自动调用
        if (ossClient() != null) {
            ossClient().shutdown();
        }
    }
}
